// Copyright (c) 2011 Blue Onion Software, All rights reserved
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IO;
using System.Xml.Serialization;
using BlueOnionSoftware.Bloget.Utility;

namespace BlueOnionSoftware.Bloget.Providers.Data
{
    [Serializable]
    [XmlRoot("users", Namespace = UserNamespace)]
    public class UserCollection : Collection<User>
    {
        internal const string UserNamespace = "urn:blueonionsoftware-com:bloget:user:data";

        public UserCollection()
        {
        }

        internal UserCollection(IList<User> array)
            : base(array)
        {
        }

        public static UserCollection Load(string fileName)
        {
            try
            {
                return Serializer.Load<UserCollection>(fileName, UserNamespace);
            }

            catch (FileNotFoundException)
            {
                return new UserCollection();
            }
        }

        public void Save(string fileName)
        {
            Serializer.Save<UserCollection>(fileName, UserNamespace, this);
        }

        public User FindByUserName(string userName)
        {
            foreach (var user in this)
            {
                if (string.Compare(user.UserName, userName, true, CultureInfo.CurrentCulture) == 0)
                {
                    return user;
                }
            }

            return null;
        }

        public User FindByEmail(string email)
        {
            foreach (var user in this)
            {
                if (string.Compare(user.Email, email, true, CultureInfo.CurrentCulture) == 0)
                {
                    return user;
                }
            }

            return null;
        }

        public User FindByKey(Guid key)
        {
            foreach (var user in this)
            {
                if (user.Key.Equals(key))
                {
                    return user;
                }
            }

            return null;
        }

        public UserCollection FindAllActiveUsers()
        {
            var users = new UserCollection();

            foreach (var user in this)
            {
                if (user.IsActive)
                {
                    users.Add(user);
                }
            }

            return users;
        }
    }
}